<template>
    <!-- 面包屑导航区域 -->
    <div class="bread_box">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/index/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card class="box-card">
          <!-- 搜索与添加区域 -->
          <el-row :gutter="20">
              <el-col :span="8">
                <el-input placeholder="请输入内容" v-model="queryInfo.queryString" clearable @clear="getUserList">
                  <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                </el-input>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
              </el-col>
          </el-row>
          <!-- 用户列表区域 -->
          <el-table :data="userlist" border stripe>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="用户编号" prop="uid"></el-table-column>
            <el-table-column label="用户名" prop="username"></el-table-column>
            <el-table-column label="密码" prop="password"></el-table-column>
            <el-table-column label="性别" prop="gender"></el-table-column>
            <el-table-column label="头像" prop="avatar"></el-table-column>
            <el-table-column label="邮箱" prop="email" width="170"></el-table-column>
            <el-table-column label="出生日期" prop="birthday" width="100"></el-table-column>
            <el-table-column label="手机" prop="mobile" width="130"></el-table-column>
            <el-table-column label="创建时间" prop="gmtCreate" width="150"></el-table-column>
            <el-table-column label="身份(0用户，1管理员)" prop="role"></el-table-column>
            <el-table-column label="操作" width="120px">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.uid)"></el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.uid)"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页器 -->
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryInfo.currentPage"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-card>
        <!-- 添加用户的对话框 -->
        <el-dialog :visible.sync="addDialogVisible" @close="addDialogClosed">
          <h1 style="color: black; margin: 0; text-align: center; font-size: 2em; font-family: STXingkai">
          注册新用户
          </h1><br><br>
          <!-- 内容主体区域 -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
            <el-form-item prop="username">
              <el-input v-model="addForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="addForm.password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item prop="gender">
              <el-select v-model="addForm.gender" placeholder="请选择性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="email">
              <el-input v-model="addForm.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
             <el-form-item prop="birthday">
              <el-date-picker v-model="addForm.birthday" type="date" value-format="yyyy-MM-dd" placeholder="请选择出生日"></el-date-picker>
            </el-form-item>
            <!-- <el-form-item label="出生日  " prop="birthday">
              <el-input v-model="addForm.birthday"></el-input>
            </el-form-item> -->
            <el-form-item prop="avatar">
              <el-input v-model="addForm.avatar" placeholder="请输入头像"></el-input>
            </el-form-item>
            <el-form-item prop="mobile">
              <el-input v-model="addForm.mobile" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item prop="role">
              <el-select v-model="addForm.role" placeholder="请选择身份">
                <el-option label="管理员" value="1"></el-option>
                <el-option label="用户" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
              <el-button @click="addDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改用户的对话框 -->
        <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
          <!-- 内容主体区域 -->
          <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username" ></el-input>
            </el-form-item>
            <el-form-item label="密码"  prop="password">
              <el-input v-model="editForm.password" ></el-input>
            </el-form-item>
            <el-form-item label="性别  " prop="gender">
              <el-select v-model="editForm.gender">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="头像" prop="avatar">
              <el-input v-model="editForm.avatar" ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" ></el-input>
            </el-form-item>
            <!-- <el-form-item label="手机" prop="mobile"> -->
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="editForm.mobile" ></el-input>
            </el-form-item>
            <el-form-item label="生日">
              <el-date-picker
                v-model="editForm.birthday"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                prop="birthday"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="身份" prop="role">
              <el-select v-model="editForm.role">
                <el-option label="管理员" value="1"></el-option>
                <el-option label="用户" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
              <el-button @click="editDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="editUserInfo(changeUid)">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^[1][0-9]{10}$/
      if (regMobile.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 要修改的uid
      changeUid: 0,
      // 获取用户列表的参数对象
      queryInfo: {
          queryString: '',
          // 当前的页数
          currentPage: 1,
          // 当前每页显示多少条数据
          pageSize: 10
      },
      userlist: [],
      total: 0,
      // 控制添加用户对话框的显示和隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        gender: '',
        birthday: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请输入性别', trigger: 'change' }
        ],
        birthday: [
          { required: true, message: '请输入出生日期', trigger: 'change' }
        ]
      },
      // 控制修改用户对话框的显示和隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请输入性别', trigger: 'change' }
        ],
        birthday: [
          { required: true, message: '请输入出生日期', trigger: 'change' }
        ]
      },
      // 用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色id值
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('/user/all.do', { params: this.queryInfo })
      console.log(res)
      this.userlist = res.rows
      this.total = res.total
      // if (this.total === 0) return this.$message.error('获取用户列表失败！')
    },
    // 监听pageSize改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pageSize = newSize
      // 页面显示的数据条数发生变化，需要重新渲染数据列表
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.currentPage = newPage
      // 页面显示的数据条数发生变化，需要重新渲染数据列表
      this.getUserList()
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 获取当前时间
    getCurrentTime() {
      var myDate = new Date()
      var year = myDate.getFullYear()
      var mon = myDate.getMonth() + 1
      var date = myDate.getDate()
      var hours = myDate.getHours()
      var minutes = myDate.getMinutes()
      var seconds = myDate.getSeconds()
      var now
      if (seconds < 10 && minutes < 10) {
      now = year + '-' + mon + '-' + date + ' ' + hours + ':0' + minutes + ':0' + seconds
      } else if (seconds < 10 && minutes > 10) {
        now = year + '-' + mon + '-' + date + ' ' + hours + ':' + minutes + ':0' + seconds
      } else if (seconds > 10 && minutes < 10) {
        now = year + '-' + mon + '-' + date + ' ' + hours + ':0' + minutes + ':' + seconds
      } else {
        now = year + '-' + mon + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds
      }
      return now
    },
    // 点击确定按钮，添加新用户
    addUser() {
      this.addForm.gmtCreate = this.getCurrentTime()
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 验证通过，则可以发起添加用户的网络请求
        console.log(this.addForm)
        const { data: res } = await this.$http.post('user/add.do', this.addForm)
        if (res.flag !== true) {
          return this.$message.error('添加用户失败！')
        }
        this.$message.success('添加用户成功！')
        // 添加用户成功后隐藏对话框
        this.addDialogVisible = false
        // 添加用户后需要重新渲染用户列表
        this.getUserList()
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog(uid) {
      this.changeUid = uid
      this.editDialogVisible = true

      const { data: res } = await this.$http.get('user/selectById.do?uid=' + uid)
      if (res.flag !== true) {
        return this.$message.error('查询用户信息失败！')
      }
      this.editForm = res.data
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        this.editForm.uid = this.changeUid
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put('user/update.do', this.editForm)
        if (res.flag !== true) {
          return this.$message.error('更新用户信息失败！')
        }
        // 关闭对话框
        this.editDialogVisible = false
        this.$refs.editFormRef.resetFields()
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功
        this.$message.success('更新用户信息成功！')
      })
    },
    // 根据id删除对应的用户信息
    async removeUserById(uid) {
      // 弹框询问用户是否删除数据
      // 返回值是一个Promise对象，可以使用async/await对象
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        // 确定按钮的文本
        confirmButtonText: '确定',
        // 取消按钮的文本
        cancelButtonText: '取消',
        // type指的是前面的小图标
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，则返回值为字符串confirm
      // 如果用户取消了删除，则返回值为字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 发起删除用户的请求
      const { data: res } = await this.$http.delete('user/remove.do?uid=' + uid)
      if (res.flag !== true) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      // 重新渲染列表
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-avatar {
  // border: 1px solid rgb(243, 219, 190);
  background-color: rgb(252, 251, 249);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 8px;
  position: relative;
  img {
    border-radius: 50%;
    width: 90%;
    height: 90%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}
span.el-dialog_title{

  font-family: STKaiti
}
</style>
